package models.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import models.entities.Module;
import models.entities.Shop;
import models.entities.Staff;
import models.enumtype.ActiveType;
import models.enumtype.KPaging;
import models.repo.IRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import utils.StringUtil;
import utils.Unicode2English;

import controllers.SessionManager;

@Service
public class ModuleDAO {
	@Autowired
	private IRepository repo;
	
	@Autowired
	private CommonDAO commonDAO;
	
	public Module createModule(Module module) throws Exception {
		if (module == null) {
			throw new IllegalArgumentException("module");
		}
		if (module.getModuleCode() != null)
			module.setModuleCode(module.getModuleCode().toUpperCase());

		Map<String, Object> loginStaff = SessionManager.get("loginStaff");
		Staff staff = (Staff) loginStaff.get("staff");
		
		module.setCreateDate(commonDAO.getSysDate());
		module.setCreateUser(staff.getStaffCode());
		
		repo.create(module);
		
		return repo.getEntityById(Module.class, module.getModuleId());
	}

	public void deleteModule(Module module) throws Exception {
		if (module == null) {
			throw new IllegalArgumentException("module");
		}
		repo.delete(module);
		
	}

	public Module getModuleById(Long id) throws Exception {
		return repo.getEntityById(Module.class, id);
	}
	
	
	public void updateShop(Module module) throws Exception {
		if (module == null) {
			throw new IllegalArgumentException("shop");
		}
		
		Map<String, Object> loginStaff = SessionManager.get("loginStaff");
		Staff staff = (Staff) loginStaff.get("staff");
		module.setUpdateUser(staff.getStaffCode());
		module.setUpdateDate(commonDAO.getSysDate());
		repo.update(module);
	}
	
	public List<Module> getListModule(KPaging<Module> kPaging, String moduleCode, String moduleName, ActiveType status) throws Exception {
		StringBuilder sql = new StringBuilder();
		List<Object> params = new ArrayList<Object>();
		sql.append("select * from modules where 1 = 1 ");
		if(!StringUtil.isNullOrEmpty(moduleCode)) {
			sql.append(" and MODULE_CODE = ?");
			params.add(moduleCode);
		}
		if(!StringUtil.isNullOrEmpty(moduleName)) {
			sql.append(" and MODULE_NAME like ? ESCAPE '/' ");
			params.add(StringUtil.toOracleSearchLike(Unicode2English.codau2khongdau(moduleName)));
		}
		if(null != status) {
			sql.append(" and STATUS = ?");
			params.add(status.getValue());
		}
		if(null != kPaging) {
			return repo.getListBySQLPaginated(Module.class, sql.toString(), params, kPaging);
		} else {
			return repo.getListBySQL(Module.class, sql.toString(), params);
		}
	}
}
